package com.story.modular.app.controller.video;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.story.common.annotion.BussinessLog;
import com.story.common.constant.Dict;
import com.story.common.constant.factory.ConstantFactory;
import com.story.common.exception.BizExceptionEnum;
import com.story.common.exception.BussinessException;
import com.story.common.persistence.dao.BannerCateMapper;
import com.story.common.persistence.dao.BannerMapper;
import com.story.common.persistence.dao.VedioCategoryMapper;
import com.story.common.persistence.model.Banner;
import com.story.common.persistence.model.BannerCate;
import com.story.common.persistence.model.VedioCategory;
import com.story.config.properties.UpyunProperties;
import com.story.core.base.controller.BaseController;
import com.story.core.support.BeanKit;
import com.story.core.util.ToolUtil;
import com.story.core.util.UriUtil;
import com.story.modular.app.dao.CateVedioDao;
import com.story.modular.app.dao.VedioCategoryDao;
import com.story.modular.app.dao.VedioDetailDao;
import com.story.modular.app.service.UpyunService;
import com.story.modular.app.transfer.CategoryDto;
import com.story.modular.app.transfer.UpdateCateDto;
import com.story.modular.app.warpper.CategoryWarpper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;

/**
 * @author Administrator
 * @decription 专辑管理
 * @Date 2017-12-21 11:30
 */
@Controller
@RequestMapping(value = "/category/video")
public class CategoryController extends BaseController{

    public static final String PREFIX = "/app/category/video/";

    private static final Long EXPIRE_TIME = 3600L;

    @Autowired
    private VedioCategoryDao vedioCategoryDao;

    @Autowired
    private BannerMapper bannerMapper;

    @Autowired
    private VedioCategoryMapper vedioCategoryMapper;

    @Autowired
    private VedioDetailDao vedioDetailDao;

    @Autowired
    private UpyunService upyunService;

    @Autowired
    private UpyunProperties upyunProperties;

    @Autowired
    private CateVedioDao cateVedioDao;

    @Autowired
    private BannerCateMapper bannerCateMapper;

    /**
     * 进入专辑列表页
     * @return
     */
    @RequestMapping(value = "")
    public String index(Model model) {
        //得到所有栏目
        List<Banner> bannerList = bannerMapper.selectList(new EntityWrapper<Banner>().eq("type",1));
        model.addAttribute("bannerList",bannerList);
        return PREFIX + "category.html";
    }

    /**
     * 进入专辑添加页面
     * @return
     */
    @RequestMapping(value = "/categoryAdd")
    public String addCategory(Model model) {
        //只查询视频部分的栏目 type = 1
        List<Banner> bannerList = bannerMapper.selectList(new EntityWrapper<Banner>().eq("type",1));
        List<Map<String,Object>> bannerMapList = new ArrayList<Map<String,Object>>();
        for(Banner banner : bannerList) {
            Map<String,Object> map = new HashMap<String,Object>();
            map.put("id",banner.getId());
            map.put("name",banner.getName());
            bannerMapList.add(map);
        }
        model.addAttribute("bannerList",bannerMapList);
        return PREFIX + "category_add.html";
    }

    /**
     * 进入批量修改页面
     * @param model
     * @return
     */
    @RequestMapping(value = "/batchUpPage")
    public String batchUpBanner(Model model) {
        //只查询视频部分的栏目 type = 1
        List<Banner> bannerList = bannerMapper.selectList(new EntityWrapper<Banner>().eq("type",1));
        List<Map<String,Object>> bannerMapList = new ArrayList<Map<String,Object>>();
        for(Banner banner : bannerList) {
            Map<String,Object> map = new HashMap<>();
            map.put("name",banner.getName());
            map.put("id",banner.getId());
            bannerMapList.add(map);
        }
        model.addAttribute("bannerList",bannerMapList);
        return PREFIX + "category_batch_up.html";
    }

    /**
     * 批量修改所属栏目
     * @param updateCateDto
     * @return
     */
    @BussinessLog(value = "批量修改", key = "id", dict = Dict.CategoryDict)
    @RequestMapping(value = "/batchUpBanner")
    @ResponseBody
    public Object batchUpBanner(UpdateCateDto updateCateDto) {
        if(ToolUtil.isOneEmpty(updateCateDto,updateCateDto.getIds(),updateCateDto.getBannerId())) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        List<Integer> idList = new ArrayList<>();
        String[] idArray = updateCateDto.getIds().split(",");
        for (String id : idArray) {
            idList.add(Integer.valueOf(id));
        }
        vedioCategoryDao.batchUpBannerId(idList,updateCateDto.getBannerId());
        vedioCategoryDao.batchUpdateBannerCate(idList,updateCateDto.getBannerId());
        return super.SUCCESS_TIP;
    }

    /**
     * 修改页面返回
     * @param categoryId
     * @param model
     * @return
     */
    @RequestMapping(value = "/categoryUpdate/{categoryId}")
    public String updateCategory(@PathVariable(value = "categoryId") Integer categoryId,
                                 Model model) {
        Map<String,Object> result = vedioCategoryDao.getCategoryById(categoryId);
        // type = 1表明只取视频部分数据
        List<Banner> bannerList = bannerMapper.selectList(new EntityWrapper<Banner>().eq("type",1));
        List<Map<String,Object>> bannerMapList = new ArrayList<Map<String,Object>>();
        for (Banner banner : bannerList) {
            Map<String,Object> map = new HashMap<String,Object>(6);
            map.put("id",banner.getId());
            map.put("name",banner.getName());
            if(result.get("bannerName").equals(banner.getName())) {
                map.put("selected","true");
            } else {
                map.put("selected","false");
            }
            bannerMapList.add(map);
        }
        result.remove("bannerName");
        result.put("bannerList",bannerMapList);
        String iconPath = (String) result.get("iconPath");
        iconPath = upyunProperties.getDomain() + iconPath + "?_upt="+ upyunService.getTokenSign(UriUtil.getUri(iconPath),EXPIRE_TIME);
        result.put("iconPath",iconPath);
        model.addAttribute("category",result);
        model.addAttribute("cName", ConstantFactory.me().getCategoryName(categoryId));
        return PREFIX + "category_update.html";
    }

    /**
     * 得到专辑列表
     * @param condition
     * @return
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(String condition,Integer bannerId) {
        if(bannerId == null || bannerId == 0) {
            bannerId = null;
        }
        //type = 1表示为视频资源
        List<Map<String,Object>> result = vedioCategoryDao.getCategoryList(condition,bannerId,1);
        result.stream().forEach(map -> map.put("iconPath",upyunProperties.getDomain() + map.get("iconPath")));
        return super.warpObject(new CategoryWarpper(result));
    }

    /**
     * 新增专辑
     * @param category
     * @return
     */
    @BussinessLog(value = "新增专辑", key = "name", dict = Dict.CategoryDict)
    @RequestMapping(value = "/add")
    @ResponseBody
    public Object add(CategoryDto category) {
        if(ToolUtil.isOneEmpty(category, category.getCategoryName(),category.getBannerList())) {
            throw new BussinessException( BizExceptionEnum.REQUEST_NULL);
        }
        VedioCategory vedioCategory = new VedioCategory();
        BeanKit.copyProperties(category, vedioCategory);
        vedioCategory.setName(category.getCategoryName());
        vedioCategory.setBannerId(category.getBannerList());
        vedioCategory.setCreateTime(new Date());
        vedioCategory.setRecRate(category.getRecRate());
        vedioCategory.setResType(1);
        int count = vedioCategoryDao.countByName(vedioCategory.getName());
        if(count > 0) {
            throw new BussinessException(BizExceptionEnum.CATE_NAME_EXIST);
        }
        vedioCategory.setIconPath(UriUtil.getUri(vedioCategory.getIconPath().split("\\?")[0]));
        vedioCategoryMapper.insert(vedioCategory);
        BannerCate bannerCate = new BannerCate();
        bannerCate.setCateId(vedioCategory.getId());
        bannerCate.setBannerId(category.getBannerList());
        bannerCateMapper.insert(bannerCate);
        return super.SUCCESS_TIP;
    }

    /**
     * 修改专辑
     * @param category
     * @return
     */
    @BussinessLog(value = "修改专辑", key = "id", dict = Dict.CategoryDict)
    @RequestMapping(value = "/update")
    @ResponseBody
    public Object updateCategory(CategoryDto category) {
        if(ToolUtil.isOneEmpty(category,category.getId(),category.getBannerList(),category.getCategoryName())) {
            throw new BussinessException( BizExceptionEnum.REQUEST_NULL);
        }
        VedioCategory vedioCategory = new VedioCategory();
        BeanKit.copyProperties( category, vedioCategory);
        vedioCategory.setName(category.getCategoryName());
        vedioCategory.setBannerId(category.getBannerList());
        vedioCategory.setResType(1);
        vedioCategory.setIconPath(UriUtil.getUri(vedioCategory.getIconPath().split("\\?")[0]));
        vedioCategoryMapper.updateById(vedioCategory);
        List<BannerCate> bannerCateList = bannerCateMapper
                .selectList(new EntityWrapper<BannerCate>().eq("cateId",vedioCategory.getId()));
        BannerCate bannerCate = bannerCateList.get(0);
        bannerCate.setBannerId(category.getBannerList());
        bannerCate.setCateId(vedioCategory.getId());
        bannerCateMapper.updateById(bannerCate);
        return super.SUCCESS_TIP;
    }

    /**
     * 删除专辑
     * @param categoryIds
     * @return
     */
    @BussinessLog(value = "删除专辑", key = "id", dict = Dict.DeleteDict)
    @RequestMapping(value = "/delete")
    @ResponseBody
    public Object deleteCategory(String categoryIds) {
        List<Integer> categoryIdList = new ArrayList<Integer>();
        String[] categoryIdArr = categoryIds.split(",");
        for (String categoryId : categoryIdArr) {
            //删除专辑和栏目的关系
            categoryIdList.add(Integer.valueOf(categoryId));
            bannerCateMapper.delete(new EntityWrapper<BannerCate>().eq("cateId",categoryId));
        }
        //解绑视频与专辑之间的关系
        cateVedioDao.batchDelRelationByCateIds(categoryIdList);
        //删除专辑
        vedioCategoryDao.batchDeleteById(categoryIdList);
        return super.SUCCESS_TIP;
    }

}
